<template>
  <el-button
    :loading="loading"
    @click="handleClick"
    v-bind="$attrs"
    v-on="$listeners"
  >
    <slot></slot>
  </el-button>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'm-button',
  props: {
    debounce: { type: Number, default: 300 },
  },
  data() {
    return {
      loading: false,
    }
  },
  methods: {
    handleClick() {
      const handler = this.$listeners.click
      if (handler) {
        this.loading = true

        const isAsync = handler.constructor.name === 'AsyncFunction'
        const done = () => {
          this.loading = false
        }

        if (isAsync) {
          handler().then(done).catch(done)
        } else {
          _.debounce(handler, this.debounce)()
        }
      }
    },
  },
}
</script>
